//
//  ScreenshotService.swift
//  LibService
//
//  Created by tank on 12/3/24.
//
import UIKit
import LibBase
import LibUI
import Logging



class ScreenshotService: ScreenshotServiceProtocol {
    var logger = Logger(label: "libService.ScreenshotService")
    
    weak var screenshotListenner: ScreenshotListenner?
    
    init() {
        logger.logLevel = .debug
    }
    
    func startListen() {
        NotificationCenter.default.addObserver(self, selector: #selector(userDidTakeScreenshot), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
    }
    
    func stopListen() {
        NotificationCenter.default.removeObserver(self, name: UIApplication.userDidTakeScreenshotNotification, object: nil)
    }
    
    @objc private func userDidTakeScreenshot() {
        guard let imageData = UIImage.ex.imageFromScreenshot()?.pngData() else {
            logger.error("获取截图数据失败")
            return
        }
        
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
            logger.error("获取缓存路径失败")
            return
        }
        
        do {
            let imagePath = cachePath + "/screenshot.png"
            
            try imageData.write(to: URL(fileURLWithPath: imagePath))
            
            screenshotListenner?.onShot(imagePath: imagePath)
        } catch {
            logger.error("写入截图失败")
        }
    }
}

